package com.example.luachtable;

import android.app.ActivityOptions;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.display.DisplayManager;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class LauncherTable extends AppCompatActivity {
    TextView launchweather, launchtime, launchcar, weatherdetals;
    Button btnapp1, btnapp2, btnapp3, btnapp4, btnapp5;
    LinearLayout layoutmusic;


    int[] imgs = new int[]{R.drawable.example_bg, R.drawable.usercenter, R.drawable.carmessage, R.drawable.music};

    String[] appTitles = new String[]{"车辆信息", "用户中心", "轮播车辆信息", "音视频"};

    private List<String> list;


    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launcher_table);

        if (Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }


        findView();


        setView();
        getLogin();


    }

    private void getLogin() {


        String url = "http://124.93.196.45:10001/dev-api/login";
        OkHttpClient client = new OkHttpClient();
        JSONObject object = new JSONObject();
        try {
            object.put("username", "16607699001");
            object.put("password", "123456");

        } catch (JSONException e) {
            e.printStackTrace();
        }


        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, String.valueOf(object));


        okhttp3.Request request = new Request.Builder().url(url).post(body).build();

        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        Toast.makeText(LauncherTable.this, "login失败。。。。。。。。。。。。", Toast.LENGTH_SHORT).show();

                    }
                });


            }


            public void onResponse(Call call, Response response) throws IOException {

                String json = response.body().string();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {


                        try {

                            JSONObject object1 = new JSONObject(json);

                            Myapp.token = object1.getString("token");
                            Toast.makeText(LauncherTable.this, "登录成功", Toast.LENGTH_SHORT).show();
                            String code = object1.getString("code");
                            if (code.equals("200")) {
                                getWeather(Myapp.token);
                                getCarMessage(Myapp.token);
                            }


                        } catch (JSONException e) {
                            throw new RuntimeException(e);
                        }

                    }
                });


            }
        });

    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    private void setView() {


        btnapp1.setOnClickListener(
                new Click()
        );
        btnapp1.setOnLongClickListener(
                new LongClick()
        );


        btnapp2.setOnClickListener(
                new Click()
        );

        btnapp2.setOnLongClickListener(
                new LongClick()
        );
        btnapp3.setOnClickListener(
                new Click()
        );
        btnapp3.setOnLongClickListener(
                new LongClick()
        );

        btnapp4.setOnClickListener(
                new Click()
        );
        btnapp4.setOnLongClickListener(
                new LongClick()
        );

        btnapp5.setOnClickListener(
                new Click()
        );
        btnapp5.setOnLongClickListener(
                new LongClick()
        );


        launchweather.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                weatherdetals.setVisibility(View.VISIBLE);

            }

        });

        launchcar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent();
        ComponentName componentName=new ComponentName("","" );
        intent.setComponent(componentName);

                startActivity(intent);

            }

        });


        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR_OF_DAY, 8);

        Date date = calendar.getTime();

        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");

        SimpleDateFormat format2 = new SimpleDateFormat("HH:mm");

        String time1=format1.format(date);

         String time2=format2.format(date);

        launchtime.setText(time1+'\n'+'\n'+time2);

    }


    private void getCarMessage(String token) {
        String url = "http://124.93.196.45:10001//dev-api/bs-vehicle-owner/carInfo/10";
        OkHttpClient client = new OkHttpClient();
        okhttp3.Request request = new Request.Builder().addHeader("Authorization", token).url(url).get().build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String json = response.body().string();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject object = new JSONObject(json);

                            JSONObject data = object.getJSONObject("data");

                            String dumpEnergy = data.getString("dumpEnergy");
                            String enduranceMileage = data.getString("enduranceMileage");
                            String temperature = data.getString("temperature");

                            launchcar.setText("车辆剩余电量：" + dumpEnergy + "\n" + "\n" + "续航里程：" + enduranceMileage + "\n" + "\n" + "车内温度：" + temperature);


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                });
            }
        });

    }


    private void getWeather(String token) {

        String url = "http://124.93.196.45:10001//dev-api/bs-weather-report/weather/10";
        OkHttpClient client = new OkHttpClient();
        okhttp3.Request request = new Request.Builder().url(url).addHeader("Authorization", token).get().build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.v("weather", "成功");
                String json = response.body().string();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject object = new JSONObject(json);

                            JSONObject data = object.getJSONObject("data");

                            int currentTemperature = data.getInt("currentTemperature");
                            String weatherDescription = data.getString("weatherDescription");
                            int humidity = data.getInt("humidity");
                            String intervalTemperature = data.getString("intervalTemperature");

                            String wind = data.getString("wind");
                            Double windVelocity = data.getDouble("windVelocity");
                            list = new ArrayList<>();
                            list.add("湿度: " + (humidity));
                            list.add("区间温度: " + intervalTemperature);
                            list.add("风向: " + wind);
                            list.add("风速: " + (windVelocity));

                            Log.v("c", String.valueOf(currentTemperature));

                            launchweather.setText("当前温度：" + currentTemperature + "\n" + "\n" + "天气情况：" + weatherDescription + "\n");

                            weatherdetals.setText("白天天气：晴" + "     " + "风向：南风" + "\n" + "晚间天气：多云  风向：东南风" + "\n" + "风速：  南风1-3级" + "\n" + "湿度： humidity: 27" + "\n" +
                                    "温度范围：" + "7~20");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                });
            }
        });

    }


    private class Click implements View.OnClickListener {
        @Override
        public void onClick(View v) {

            if (v.getTag() == null) {
                setupApp(v);
            } else {
                switch ((int)v.getTag()) {

                    case 0:

                   


                    case 1:




                        Toast.makeText(LauncherTable.this, "用户中心", Toast.LENGTH_SHORT).show();
                        break;

                    case 2:
                        Intent intent2 = new Intent(LauncherTable.this, Carmessage.class);

                        startActivity(intent2);
                        Toast.makeText(LauncherTable.this, "轮播车辆信息", Toast.LENGTH_SHORT).show();

                        break;
                    case 3:
                        Intent intent3 = new Intent(LauncherTable.this, MediaMusic.class);

                        startActivity(intent3);
                        Toast.makeText(LauncherTable.this, "音视频", Toast.LENGTH_SHORT).show();

                        break;
                }


            }
        }

    }



    private void setupApp(View v) {

            final AlertDialog.Builder builder = new AlertDialog.Builder(LauncherTable.this);


            builder.setTitle("请选择APP");
            builder.setItems(appTitles, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    v.setBackgroundResource(imgs[which]);

                    v.setTag(which);

                }
            });

            builder.show();

        }

        private void findView() {
            launchcar = findViewById(R.id.launchcar);
            launchweather = findViewById(R.id.launchweather);
            launchtime = findViewById(R.id.launchtime);
            layoutmusic = findViewById(R.id.layoutmusic);
            btnapp1 = findViewById(R.id.btnapp1);
            btnapp2 = findViewById(R.id.btnapp2);
            btnapp3 = findViewById(R.id.btnapp3);
            btnapp4 = findViewById(R.id.btnapp4);
            btnapp5 = findViewById(R.id.btnapp5);
            weatherdetals = findViewById(R.id.weatherdetals);
        }

        private class LongClick implements View.OnLongClickListener {
            @Override
            public boolean onLongClick(View view) {

                 PopupMenu popupMenu=new PopupMenu(LauncherTable.this,view);
                 Menu menu=popupMenu.getMenu();
                 menu.add(Menu.NONE,Menu.FIRST+1,1,"替换其App");

                menu.add(Menu.NONE, Menu.FIRST + 2, 1, "副屏启动");


                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
                    @Override
                    public boolean onMenuItemClick(MenuItem menuItem) {

                        switch (menuItem.getItemId()) {

                            case Menu.FIRST + 1:

                                setupApp(view);
                                break;
                            case Menu.FIRST + 2:

                                getFuping1((int) view.getTag());

                                break;

                        }

                        return false;
                    }
                });

                popupMenu.show();

                return false;
            }
        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
        private void getFuping1(int view) {
            DisplayManager displayManager = (DisplayManager) LauncherTable.this.getSystemService(Context.DISPLAY_SERVICE);
            Display[] displays = displayManager.getDisplays();
            if (displays.length > 1) {


                Intent intent = new Intent(LauncherTable.this, FuPing.class);

                intent.putExtra("pos", view);

                intent.setClassName(getPackageName(), getPackageName() + ".FuPing");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

                ActivityOptions options = null;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    options = ActivityOptions.makeBasic();
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    options.setLaunchDisplayId(displays[1].getDisplayId());
                }
                startActivity(intent, options.toBundle());


            }

        }
    }


